package com.fuyao.cloud.admin.flow.service.flowable.impl;

import com.fuyao.cloud.admin.flow.model.User;
import com.fuyao.cloud.admin.flow.service.flowable.IFlowableModelService;
import com.fuyao.cloud.admin.flow.service.flowable.IModelInfoService;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.security.service.CloudUser;
import lombok.extern.slf4j.Slf4j;
import org.flowable.dmn.editor.converter.DmnJsonConverter;
import org.flowable.dmn.xml.converter.DmnXMLConverter;
import org.flowable.ui.modeler.domain.Model;
import org.flowable.ui.modeler.model.ModelKeyRepresentation;
import org.flowable.ui.modeler.model.ModelRepresentation;
import org.flowable.ui.modeler.serviceapi.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class FlowableModelServiceImpl implements IFlowableModelService {

    @Autowired
    private ModelService modelService;
    @Autowired
    protected DmnXMLConverter dmnXMLConverter;
    @Autowired
    protected DmnJsonConverter dmnJsonConverter;
    @Autowired
    protected IModelInfoService modelInfoService;

    @Override
    public R<Model> createModel(ModelRepresentation modelRepresentation, CloudUser user) {
        modelRepresentation.setKey(modelRepresentation.getKey().replaceAll(" ", ""));
        ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(null, modelRepresentation.getModelType(), modelRepresentation.getKey());
        if (modelKeyInfo.isKeyAlreadyExists()){
           return R.failed("KEY 不能重复");
        }
        String json = modelService.createModelJson(modelRepresentation);
        Model newModel = modelService.createModel(modelRepresentation, json, user.getUsername());
        return R.ok(newModel);
    }
}
